package com.hzdl.house_mgr.controller;

import com.hzdl.house_mgr.mapper.HouseMapper;
import com.hzdl.house_mgr.service.HouseService;
import com.hzdl.house_mgr.util.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private HouseMapper houseMapper;

    @RequestMapping("uploadFiles")
    @ResponseBody
    public Map<String,Object> uploadFile(MultipartFile [] mfs, HttpSession session,Integer houseId){

        Map<String,Object> map=new HashMap<>();
        map.put("code", 0);
        map.put("msg", "上传成功");

        for(MultipartFile mf:mfs) {
            // 1,得到老名字
            String oldName = mf.getOriginalFilename();
            // 2,得到tomcat里面的upload目录
            String realPath = session.getServletContext().getRealPath(
                    "/static/images/");
            // 3,得到当前时间2018-07-14
            // 4,得到新的父目录的路径 并判断是否存在 如果不存在就创建
            String newRealPath = "C:\\Users\\XBB\\Desktop\\house_mgr\\src\\main\\resources\\static\\images";
            File parentFile = new File(newRealPath);
            if (!parentFile.exists()) {
                parentFile.mkdirs();// 创建文件夹
            }
            // 5,得到新名字
            String newName = oldName;
            // 6,构造文件
            File file = new File(parentFile, newName);
            // 7，上传
            try {
                mf.transferTo(file);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
            Map<String, Object> data = new HashMap<>();
            //此处可修改保存路径格式

            String src = "/house/static/images/" + newName;
            data.put("src", src);
            map.put("data", data);
            houseMapper.insertImg(houseId, src);
        }
        return map;
    }
}
